<!--
 * @author guojiteng
 -->
<template>
  <div id="label-list">
    <div v-show="searchshow" class="label-list-search">
      <el-collapse-transition>
        <div v-show="searchshow" class="course-search merge">
          <span class="svg-container">
            <svg-icon icon-class="search" />
          </span>
          <el-input
            v-model.trim="listQuery.commonParam"
            placeholder="请输入关键字搜索"
            class="search-input"
          />
          <div class="course-search-btn">
            <el-button class="filter-item" type="primary" @click="handleFilter"
              >搜索</el-button
            >
            <el-button class="filter-item" type="primary" @click="resettingBtn"
              >重置</el-button
            >
            <span class="course-search-more" @click="searchshow = !searchshow">
              更多筛选条件
              <i class="el-icon-arrow-down" />
            </span>
          </div>
        </div>
      </el-collapse-transition>
    </div>

    <el-collapse-transition>
      <div v-show="!searchshow" class="course-search separate">
        <div class="course-search-inner">
          <el-row>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">标签</div>
                <el-input
                  v-model.trim="search.tag"
                  style="width: 80%"
                  class="filter-item"
                  placeholder="请输入标签搜索"
                />
              </div>
            </el-col>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">状态</div>
                <el-checkbox-group
                  v-model="search.status"
                  style="margin-top: 10px"
                  :max="1"
                >
                  <el-checkbox :label="null">全部</el-checkbox>
                  <el-checkbox label="ZT01">启用</el-checkbox>
                  <el-checkbox label="ZT02">禁用</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="course-search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter"
            >搜索</el-button
          >
          <el-button class="filter-item" type="primary" @click="resettingBtn"
            >重置</el-button
          >
          <span class="course-search-more" @click="searchshow = !searchshow">
            精简筛选条件
            <i class="el-icon-arrow-up" />
          </span>
        </div>
      </div>
    </el-collapse-transition>

    <div class="btn-container">
      <div class="btn-container-title">标签列表</div>
      <el-button
        v-if="!!!isComponent"
        class="filter-item"
        style="margin-left: 10px"
        @click="labelCount"
        >重新统计引用数量</el-button
      >
    </div>
    <div class="table">
      <el-table
        ref="multipleTable"
        :list-loading="listLoading"
        :data="list"
        style="width: 100%"
        stripe
        :row-key="getRowKey"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          :reserve-selection="true"
        />
        <el-table-column prop="name" label="标签名称" width="150px" />
        <el-table-column
          prop="classifyName"
          label="分类名称"
          show-overflow-tooltip
        />
        <el-table-column
          prop="quoteNum"
          label="引用数量"
          show-overflow-tooltip
        />
        <el-table-column
          prop="statusValue"
          label="状态"
          show-overflow-tooltip
        />
        <el-table-column
          prop="statisticalTime"
          label="统计时间"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="!!!isShow"
          label="操作"
          fixed="right"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              v-if="!!isComponent"
              type="text"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
            <el-button
              v-if="!!!isComponent"
              type="text"
              @click="changeStatus(scope.row)"
              >{{ scope.row.status === "ZT01" ? "禁用" : "启用" }}</el-button
            >
            <!-- <el-button type="text" @click="handleView(scope.row)">查看</el-button>  -->
            <el-button
              v-if="!!!isComponent"
              type="text"
              @click="handleSelectType(scope.row)"
              >分类</el-button
            >
            <el-button type="text" @click="handleAddress(scope.row.name)"
              >查看地址</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="btn-pagion fix">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </div>

    <el-dialog
      v-el-drag-dialog
      title="分类"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      center
    >
      <section class="content">
        <el-checkbox-group v-model="selectTypeList">
          <el-tree
            :data="treeData"
            node-key="id"
            :props="defaultProps"
            :default-expand-all="true"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <el-checkbox :label="data.id">{{ data.name }}</el-checkbox>
            </span></el-tree
          >
        </el-checkbox-group>
      </section>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px" @click="handleCancel()"
          >取消</el-button
        >
        <el-button style="padding: 8px 30px" type="primary" @click="handleSubim"
          >确定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      v-el-drag-dialog
      title="查看"
      :visible.sync="dialogForm4Visible"
      :close-on-click-modal="false"
      center
      @close="handleCloseView"
    >
      <section class="content">
        <el-form ref="form" :model="viewFrom" label-width="120px">
          <el-form-item label="标签">{{ viewFrom.name }}</el-form-item>
          <el-form-item label="所属分类">{{
            viewFrom.classifyName
          }}</el-form-item>
          <el-form-item label="引用数量">{{ viewFrom.quoteNum }}</el-form-item>
          <el-form-item label="上次统计时间">{{
            viewFrom.statisticalTime
          }}</el-form-item>
        </el-form>
      </section>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px" @click="dialogForm4Visible = false"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { queryPage, getDictByCode, hylabelType, insertClassify, labelCount, updateStatus, querySelectTypes, queryDetail, deleteLabel } from '../api/index'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import CryptoJS from '@/utils/aesJiaJM'
import elDragDialog from '@/directive/el-drag-dialog'
export default {
  name: 'LabelList',
  components: { Pagination },
  directives: { elDragDialog },
  props: ['classifyId', 'isComponent', 'isShow'],
  data() {
    return {
      chooseArr: [],
      listQuery: {
        page: 1,
        limit: 10,
        commonParam: ''
      },
      searchshow: true,
      search: {
        tag: '',
        status: []
      },
      list: [],
      total: 0,
      listLoading: false,
      dict: {
      },
      treeData: [],
      dialogFormVisible: false,
      selectRow: {},
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      selectTypeList: [],
      viewFrom: {},
      dialogForm4Visible: false,
      link: '/studyList?t=l&i='
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  created() {
    for (const key in this.dict) {
      this.getDict(key)
    }
    this.getList()
  },
  methods: {
    // 列表选择
    handleSelectionChange(val) {
      this.chooseArr = val
      this.$emit('checked', val)
    },
    filtercolumn(scope, item) {
      if (item === 'userIdnumber' || item === 'phoneNumber') {
        return CryptoJS.$aesJieM(scope.row[item])
      } else {
        return scope.row[item]
      }
    },
    /**
     * 解密
     */
    handleDecrypt(str) {
      return CryptoJS.$aesJieM(str)
    },
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(response => {
          this.dict[code] = response.data.data && response.data.data.length > 0 ? response.data.data[0].list : []
        })['catch'](error => {
          reject(error)
        })
      })
    },

    /**
     * 查询列表
     */
    getList(obj) {
      const _this = this
      var query = {
        'page': obj ? obj.page : this.listQuery.page,
        'pageSize': obj ? obj.limit : this.listQuery.limit,
        'classifyId': this.classifyId ? this.classifyId : ''
      }
      if (this.searchshow) {
        query.name = this.listQuery.commonParam
      } else {
        query.status = this.search.status[0]
        query.name = this.search.tag
      }
      this.listLoading = true
      return new Promise((resolve, reject) => {
        queryPage(query).then(response => {
          this.list = response.data.data.rows
          this.total = response.data.data.total
          _this.listLoading = false
        })['catch'](error => {
          reject(error)
          _this.listLoading = false
        })
      })
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resettingBtn() {
      this.checkAllFlag = false
      this.listQuery.commonParam = ''
      this.listQuery.page = 1
      for (const i in this.search) {
        if (this.search[String(String(i))] instanceof Array) {
          this.search[String(String(i))] = []
        } else {
          this.search[String(String(i))] = ''
        }
      }
      this.checkAllFlag = true
      this.timer = new Date().getTime()
      this.getList()
    },
    getLabelTypeList() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return new Promise((resovle, reject) => {
        hylabelType({ type: 'FLLX_XXBQ' }).then(res => {
          loading.close()
          this.treeData = res.data.data
          resovle(res.data.data)
        })
      })
    },
    handleSelectType(row) {
      this.selectRow = row
      const list = [this.querySelectTypes(row), this.getLabelTypeList()]
      Promise.all(list).then(res => {
        const [selectTypes] = res
        this.$nextTick(() => {
          this.selectTypeList = selectTypes || []
          this.dialogFormVisible = true
        })
      })
    },
    handleCancel() {
      this.selectTypeList = []
      this.dialogFormVisible = false
    },
    handleSubim() {
      if (this.selectTypeList.length < 1) {
        return this.$message({
          type: 'warning',
          message: '请选择标签类型'
        })
      }
      const setParmas = {
        labelId: this.selectRow.id,
        classifyId: this.selectTypeList.join(',')

      }
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      insertClassify(setParmas).then(res => {
        loading.close()
        if (res.data.code === '200') {
          this.handleCancel()
          this.$message({
            type: 'success',
            message: '操作成功'
          })
        }
        this.getList()
      }).catch(err => {
        loading.close(err)
      })
    },
    labelCount() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      labelCount().then(res => {
        loading.close()
        this.$message({
          type: 'success',
          message: res.data.data
        })
        this.getList()
      }).catch(err => loading.close(err))
    },
    /**
     * 切换启用禁用状态
     */
    changeStatus(row) {
      if (!row.id) {
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const status = row.status === 'ZT01' ? 'ZT02' : 'ZT01'
      return new Promise((resolve, reject) => {
        updateStatus({ id: row.id, status }).then(() => {
          this.$message({
            message: '处理成功',
            type: 'success',
            duration: 2000
          })
          loading.close()
          this.getList()
        }).catch(error => {
          loading.close()
          this.getList()
          reject(error)
        })
      })
    },
    querySelectTypes(row) {
      return new Promise((resolve, reject) => {
        querySelectTypes({ labelId: row.id }).then(
          res => {
            // this.selectRow = res.data.data || []
            resolve(res.data.data)
          }
        )
      })
    },
    handleView(row) {
      if (row.id) {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        queryDetail({ id: row.id }).then(res => {
          loading.close()
          this.viewFrom = res.data.data
          this.dialogForm4Visible = true
        }).catch(err => {
          loading.close(err)
        })
      }
    },
    handleCloseView() {
      this.getList()
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该标签, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        deleteLabel({ labelId: row.id, classifyId: this.classifyId }).then(res => {
          loading.close()
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getList()
        }).catch(() => { loading.close() })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    getRowKey(row) {
      return row.id
    },

    /**
       * 查看前端地址
       */
    handleAddress(name) {
      this.$confirm(`链接地址为：${this.link}${name}<span style="color:red">注意：该链接只对已发布数据有效</span>`, '提示', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '复制链接',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const input = document.createElement('input')
        input.setAttribute('readonly', 'readonly')
        input.setAttribute('value', this.link + name)
        document.body.appendChild(input)
        input.select()
        if (document.execCommand('copy')) {
          document.execCommand('copy')
          this.$message({
            title: '成功',
            message: '复制成功！',
            type: 'success',
            duration: 1500
          })
        }
        document.body.removeChild(input)
      }).catch(() => {

      })
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" type="text/scss">
$dark_gray: #bfced6;
@import "@/styles/mixin.scss";
.el-dropdown-menu {
  max-height: 400px !important;
  overflow: auto;
}
#label-list {
  padding: 10px;

  .label-list-search {
    background-color: #fff;
    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;
      &_login {
        font-size: 20px;
      }
    }
    .search-input {
      width: 78%;
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .el-button.is-round {
      float: right;
      padding: 10px 30px;
    }
  }
  .course-search {
    background-color: #fff;
    padding: 0 10px;
    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;
      &_login {
        font-size: 20px;
      }
    }
    .search-input {
      width: 50%;
      position: relative;
      &:after {
        content: "";
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .course-search-btn {
      display: inline-block;
      float: right;
      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }
      .course-search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }
    &.merge {
      height: 50px;
      line-height: 50px;
    }
    &.separate {
      .course-search-inner {
        padding-top: 10px;
        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #333333;
            font-weight: 700;
          }
          .el-input {
            position: relative;
            .el-input__inner {
              border: none;
              padding: 0;
            }
            &:after {
              content: "";
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }
      .course-search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }
  .btn-container {
    display: flex;
    margin-top: 5px;
    align-items: center;
    margin-bottom: 5px;
    .btn-container-title {
      flex: 1;
      font-size: 16px;
      font-weight: bold;
      color: #333;
      padding: 0 10px;
      .el-dropdown-link {
        cursor: pointer;
        @include font-color($mainColor);
      }
    }
    .selectOrg {
      margin-left: 10px;
    }
    .box {
      width: 100%;
    }
    .draw-enter-active,
    .draw-leave-active {
      transition: all 1s ease;
    }
    .draw-enter, .draw-leave-to /* .fade-leave-active below version 2.1.8 */ {
      width: 0;
    }
  }
  .content {
    display: flex;
    height: 500px;
    overflow: auto;
  }
}
</style>

